﻿using System;
using Newtonsoft.Json;
using XCI.Helper;

namespace XCI.Core
{
    /// <summary>
    /// Json对象配置文件
    /// </summary>
    public class JsonFile<T> where T : class, new()
    {
        /// <summary>
        /// 配置文件路径
        /// </summary>
        public string Path { get; private set; }

        /// <summary>
        /// 配置数据
        /// </summary>
        public T Data { get; private set; }

        /// <summary>
        /// 初始化Json对象配置文件
        /// </summary>
        public JsonFile()
        {
        }

        /// <summary>
        /// 使用指定文件路径初始化Json对象配置文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public JsonFile(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentException("请指定配置文件路径", nameof(Path));
            this.Load(path);
        }

        /// <summary>
        /// 从指定文件中重新加载配置数据
        /// </summary>
        /// <param name="path">文件路径</param>
        public void Load(string path)
        {
            this.Path = path;
            this.Load();
        }

        /// <summary>
        /// 从文件中加载配置数据
        /// </summary>
        public void Load()
        {
            this.Data = JsonHelper.FromJsonFile(Path, new T());
        }

        /// <summary>
        /// 保存配置数据到文件中
        /// </summary>
        public void Save(JsonSerializerSettings setting = null)
        {
            if (setting == null)
            {
                setting = JsonHelper.GetDefaultSetting(Formatting.Indented);
            }
            JsonHelper.ToJsonFile(Path, Data, setting);
        }

        /// <summary>
        /// 设置数据对象
        /// </summary>
        /// <param name="data">数据对象</param>
        public void SetData(T data)
        {
            this.Data = data;
        }
    }
}